package com.summerbird.mallchat.common.common.event.listener;

import com.summerbird.mallchat.common.chat.dao.MessageDao;
import com.summerbird.mallchat.common.chat.dao.MessageMarkDao;
import com.summerbird.mallchat.common.chat.domain.dto.ChatMessageMarkDTO;
import com.summerbird.mallchat.common.chat.domain.entity.Message;
import com.summerbird.mallchat.common.chat.domain.enums.MessageMarkTypeEnum;
import com.summerbird.mallchat.common.chat.domain.enums.MessageTypeEnum;
import com.summerbird.mallchat.common.common.event.MessageMarkEvent;
import com.summerbird.mallchat.common.user.domain.enums.IdempotentEnum;
import com.summerbird.mallchat.common.user.domain.enums.ItemEnum;
import com.summerbird.mallchat.common.user.service.UserBackpackService;
import com.summerbird.mallchat.common.user.service.impl.PushService;
import com.summerbird.mallchat.common.websocket.service.adapter.WebSocketAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Objects;

@Slf4j
@Component
public class MessageMarkListener {

    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageMarkDao messageMarkDao;
    @Autowired
    private UserBackpackService userBackpackService;
    @Autowired
    private PushService pushService;
    @TransactionalEventListener(classes = MessageMarkListener.class, fallbackExecution = true)
    public void changeMsgType(MessageMarkEvent event) {
        ChatMessageMarkDTO dto = event.getDto();
        Message message = messageDao.getById(dto.getMsgId());
        if(!Objects.equals(message.getType(), MessageTypeEnum.TEXT.getType())){// 普通消息才需要升级
            return;
        }
        // 消息标记的次数
        Integer markCount = messageMarkDao.getMarkCount(dto.getMsgId(), dto.getMarkType());
        MessageMarkTypeEnum markTypeEnum = MessageMarkTypeEnum.of(dto.getMarkType());
        if(markCount < markTypeEnum.getRiseNum()){
            return;
        }
        if(MessageMarkTypeEnum.LIKE.getType().equals(dto.getMarkType())){ // 点赞达到数量，送个徽章
            userBackpackService.acquireItem(dto.getUid(), ItemEnum.LIKE_BADGE.getId(), IdempotentEnum.MAS_ID, message.getId().toString());
        }
    }

    @TransactionalEventListener(classes = MessageMarkListener.class, fallbackExecution = true)
    public void notifyAll(MessageMarkEvent event) {//后续可做合并查询，目前异步影响不大
        ChatMessageMarkDTO dto = event.getDto();
        Integer markCount = messageMarkDao.getMarkCount(dto.getMsgId(), dto.getMarkType());
        pushService.sendPushMsg(WebSocketAdapter.buildMsgMarkSend(dto, markCount));
    }
}
